package com.weavernorth.WeChatWork;

import com.alibaba.fastjson.JSONObject;
import com.weavernorth.util.Logger4jUtil;
import org.apache.bcel.generic.I2F;
import org.apache.log4j.Logger;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import static com.weavernorth.util.HttpUtil.isHostReachable;

/**
 * @Author: zl
 * @Package: com.weavernorth.WeChatWork
 * @date: 2021/6/4 15:00
 * @description: 调用企业微信接口创建群聊//implements Action {
 */
public class CreateGroupChat implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {/*RequestInfo requestInfo*/
        Logger log = Logger4jUtil.getLoggerByName("/WeChatWork/CreateGroupChat/");
        //企微接口地址：https://qyapi.weixin.qq.com/cgi-bin/gettoken
        //中转地址：https://www.erdosssl.cn/wework/cgi-bin/
        log.info("企业微信创建群聊流程开始...");
        RecordSet rs = new RecordSet();
        //请求id
        String strRequestid = requestInfo.getRequestid();
        log.info("流程requestid=" + strRequestid);

        StringBuffer sbSql = new StringBuffer();
        List<String> ltSJH = new ArrayList<String>();
        sbSql.append("select * from formtable_main_901 where REQUESTID =");
        sbSql.append(strRequestid);
        log.info("执行查询语句：" + sbSql);
        String strQzsjh = "";//群主手机号
        String strQlmc = "";//群聊名称
        String strCjcghfsdnr = "";//创建成功后发送的内容
        String Id = "";
        String strQLIDXGYQYWX = "";//修改群聊的chatId
        rs.executeQuery(sbSql.toString());
        while (rs.next()) {
            Id = Util.null2String(rs.getString("ID"));
            strQzsjh = Util.null2String(rs.getString("QZSJH"));
            strQlmc = Util.null2String(rs.getString("QLMC"));
            strCjcghfsdnr = Util.null2String(rs.getString("CJCGHFSDNR"));
            strQLIDXGYQYWX = Util.null2String(rs.getString("QLIDXGYQYWX"));
            log.info("群主手机号：" + strQzsjh);
            log.info("群聊名称：" + strQlmc);
            log.info("创建成功后发送的内容：" + strCjcghfsdnr);
            log.info("群聊ID【为空则为新增】：" + strQLIDXGYQYWX);
        }
        //查询明细
        sbSql.setLength(0);
        //sbSql.append("select * from formtable_main_901_dt1 where MAINID = ");
        sbSql.append("select * from formtable_main_901_dt2 where MAINID = ");
        sbSql.append(Id);
        rs.executeQuery(sbSql.toString());
        while (rs.next()) {
            String[] splitSjh = Util.null2String(rs.getString("SJH")).split(",");
            //ltSJH.add(Util.null2String(rs.getString("SJH")));
            for (int i = 0; i < splitSjh.length; i++) {
                ltSJH.add(splitSjh[i]);
                log.info("群聊成员手机号：" + splitSjh[i]);
            }
        }

        //添加群主手机号
        if (!ltSJH.contains(strQzsjh)) {
            ltSJH.add(strQzsjh);
        }
        String param = "corpid="+HttpConst.corpid+"&corpsecret="+HttpConst.corpsecret+"&debug=1";
        // param = String.format(param, "wx5f34d343e1647474", "lFOjj4xSWpbjC49Abh-xKqFaxsc9JDe_WbiJmQSKt1w");
        // String postUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx5f34d343e1647474&corpsecret=lFOjj4xSWpbjC49Abh-xKqFaxsc9JDe_WbiJmQSKt1w&debug=1";
        try {
            //企业微信API步骤一.获取AccessToken
            log.info("开始获取企业微信AccessToken...");
//            if (!isHostReachable("qyapi.weixin.qq.com", 6000)) {
//                String hostAddress = InetAddress.getByName("qyapi.weixin.qq.com").getHostAddress();
//                log.info("连接超时,qyapi.weixin.qq.com对应ip地址：" + hostAddress);
//                requestInfo.getRequestManager().setMessagecontent("获取企业微信AccessToken失败,连接超时");
//                return FAILURE_AND_CONTINUE;
//            }

            String jsonAccessToken = HttpRequestUtil.sendGet(HttpConst.baseUrl + "gettoken", param,log);
            log.info("jsonAccessToken：" + jsonAccessToken);
            JSONObject jsonObject = JSONObject.parseObject(jsonAccessToken);
            int errcode = jsonObject.getIntValue("errcode");
            if (errcode != 0) {
                //始获取企业微信AccessToken失败
                requestInfo.getRequestManager().setMessagecontent("获取企业微信AccessToken失败：" + jsonAccessToken);
                log.info("获取企业微信AccessToken失败：" + jsonAccessToken);
                return FAILURE_AND_CONTINUE;
            }
            String AccessToken = jsonObject.getString("access_token");
            log.info("AccessToken:" + AccessToken);
            StringBuffer sbJsonData = new StringBuffer();
            StringBuffer sbJsonUserList = new StringBuffer();
            String jsonResult = "";
            String qzUserId = "";
            //企业微信API步骤二.根据手机号获取userid
            String postUrl = HttpConst.baseUrl + "user/getuserid?access_token=" + AccessToken;
            int ltSize = ltSJH.size();
            for (int i = 0; i < ltSize; i++) {
                String strSJH = ltSJH.get(i);
                sbJsonData.setLength(0);
                sbJsonData.append("{ \"mobile\": \"");
                sbJsonData.append(strSJH);
                sbJsonData.append("\"}");
                log.info("根据手机号获取用户ID【getuserid】JSON:" + sbJsonData);
                jsonResult = HttpRequestUtil.sendPost(postUrl, sbJsonData.toString());
                log.info("获取用户ID返回的JSON:" + jsonResult);
                jsonObject = JSONObject.parseObject(jsonResult);
                sbJsonUserList.append("\"");
                sbJsonUserList.append(jsonObject.getString("userid"));
                sbJsonUserList.append("\"");
                if ((i + 1) < ltSize) {
                    sbJsonUserList.append(",");
                }
                if (strQzsjh.equals(strSJH)) {
                    qzUserId = jsonObject.getString("userid");
                }
            }
            log.info("用户列表：" + sbJsonUserList.toString());

            if (null != strQLIDXGYQYWX && strQLIDXGYQYWX.length() > 4) //修改流程
            {
                //修改群聊
                postUrl = HttpConst.baseUrl + "appchat/update?access_token=" + AccessToken;
                sbJsonData.setLength(0);
                sbJsonData.append("{\"chatid\":\"");
                sbJsonData.append(strQLIDXGYQYWX);
                sbJsonData.append("\",\"name\":\"");
                sbJsonData.append(strQlmc);
                sbJsonData.append("\",\"owner\":\"");
                sbJsonData.append(qzUserId);
                sbJsonData.append("\",\"add_user_list\":[");
                sbJsonData.append(sbJsonUserList);
                sbJsonData.append("],\"del_user_list\":[]");
                sbJsonData.append("}");
                log.info("调用修改群聊接口Post Json Body:" + sbJsonData);
                jsonResult = HttpRequestUtil.sendPost(postUrl, sbJsonData.toString());
                log.info("创建修改返回结果JSON:" + jsonResult);
                jsonObject = JSONObject.parseObject(jsonResult);
                errcode = jsonObject.getIntValue("errcode");
                if (errcode != 0) {
                    //修改群聊失败
                    requestInfo.getRequestManager().setMessagecontent("修改群聊失败：" + jsonResult);
                    return FAILURE_AND_CONTINUE;
                }
            } else {
                //企业微信API步骤三.创建群聊会话
                log.info("3.1开始创建群聊会话...");
                postUrl = HttpConst.baseUrl + "appchat/create?access_token=" + AccessToken;
                sbJsonData.setLength(0);
                sbJsonData.append("{");
                sbJsonData.append("\"name\": \"");
                sbJsonData.append(strQlmc);
                sbJsonData.append("\",");
                sbJsonData.append("\"owner\": \"");
                sbJsonData.append(qzUserId);
                sbJsonData.append("\",");
                sbJsonData.append("\"userlist\": [");
                sbJsonData.append(sbJsonUserList);
                sbJsonData.append("],");
                sbJsonData.append("\"chatid\": \"\"");
                sbJsonData.append("}");
                log.info("调用创建群聊接口Post Json Body:" + sbJsonData);
                jsonResult = HttpRequestUtil.sendPost(postUrl, sbJsonData.toString());
                log.info("创建群聊返回结果JSON:" + jsonResult);
                jsonObject = JSONObject.parseObject(jsonResult);

                errcode = jsonObject.getIntValue("errcode");
                if (errcode != 0) {
                    //创建群聊失败
                    requestInfo.getRequestManager().setMessagecontent("创建群聊失败：" + jsonResult);
                    return FAILURE_AND_CONTINUE;
                }
                String strChatId = jsonObject.getString("chatid");
                //更新chatid
                sbSql.setLength(0);
                sbSql.append("Update formtable_main_901 set QLIDXTZDSC='");
                sbSql.append(strChatId);
                sbSql.append("' where REQUESTID = ");
                sbSql.append(strRequestid);
                log.info("更新chatid:" + sbSql);
                rs.execute(sbSql.toString());

                //企业微信API步骤四.推送消息 这个和修改接口需要单独接口
                log.info("4.1会话创建完成推送一条消息...");
                sbJsonData.setLength(0);
                postUrl = HttpConst.baseUrl + "appchat/send?access_token=" + AccessToken;
                sbJsonData.append("{\"chatid\": \"");
                sbJsonData.append(strChatId);
                sbJsonData.append("\",\"msgtype\":\"text\",\"text\":{");
                sbJsonData.append("\"content\" : \"");
                sbJsonData.append(strCjcghfsdnr);
                sbJsonData.append("\"");
                sbJsonData.append("},\"safe\":0}");
                log.info("3.2推送消息JSON:" + sbJsonData);
                jsonResult = HttpRequestUtil.sendPost(postUrl, sbJsonData.toString());
                log.info("3.3推送消息返回结果JSON:" + jsonResult);
                jsonObject = JSONObject.parseObject(jsonResult);
                errcode = jsonObject.getIntValue("errcode");
                if (errcode != 0) {
                    //群聊创建成功发送消息失败
                    requestInfo.getRequestManager().setMessagecontent("群聊创建成功，消息发送失败：" + jsonResult);
                    return FAILURE_AND_CONTINUE;
                }
            }

            return SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            log.info(e.getMessage());
            requestInfo.getRequestManager().setMessagecontent("企业微信接口创建群聊失败：" + e.toString());
            return FAILURE_AND_CONTINUE;
        }
    }
}
